class Solution {
    public boolean[][] flag;
    public int m;
    public int n;
    public boolean exist(char[][] board, String word) {
        char[] ch=word.toCharArray();
        m=board.length;
        n=board[0].length;
        flag=new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(board[i][j]==ch[0] && !flag[i][j]){
                    flag[i][j]=true;
                    if(dfs(board,ch,1,i,j)){
                        return true;
                    }
                    flag[i][j]=false;
                }
            }
        }
        return false;
    }
    public int[] dx={1,0,-1,0};
    public int[] dy={0,1,0,-1};
    public boolean dfs(char[][] board,char[] ch,int pos,int a,int b){
        if(pos== ch.length){
            return true;
        }
        for(int i=0;i<4;i++){
            int x=a+dx[i];
            int y=b+dy[i];
            if(x>=0 && x<m && y>=0 && y<n){
                if(board[x][y]==ch[pos] && !flag[x][y]){
                    flag[x][y]=true;
                    if(dfs(board,ch,pos+1,x,y)){
                        return true;
                    }
                    flag[x][y]=false;
                }
            }
        }
        return false;
    }
}